package com.example.codefilter.framework.security.handle;

import com.alibaba.fastjson2.JSON;
import com.example.codefilter.common.constant.HttpStatus;
import com.example.codefilter.common.core.AjaxResult;
import com.example.codefilter.common.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 登录失败处理器
 *
 * @author LiJunYi
 * @date 2022/07/27
 */
@Component
@Slf4j
public class CustomAuthenticationFailureImpl implements AuthenticationFailureHandler
{

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error(e.getMessage());
        String msg = "验证码";
        if (e.getMessage().contains(msg))
        {
            int code = HttpStatus.ERROR;
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, e.getMessage())));
        }else
        {
            int code = HttpStatus.UNAUTHORIZED;
            msg = "用户名或密码错误";
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
        }
    }
}
